package com.webserver.core;

import com.sun.javafx.binding.StringFormatter;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class DispatcherServlet {
    public void service(HttpServletRequest request, HttpServletResponse response){
        //2.处理请求
        String path=request.getUri();
        System.out.println("请求抽象路径:"+path);
        File file=new File("./webapps"+path);
        //状态相关信息

        if (file.isFile()){
            response.setContentFile(file);
            String fileName=file.getName();
            System.out.println("请求的资源文件名为:"+fileName);
            /*
            1.根据文件名获取后缀
            2.根据后缀来设置Content-Type对应的值
             */

            Map<String,String> mimeMapping=new HashMap<>();
            mimeMapping.put("html","text/html");
            mimeMapping.put("css","text/css");
            mimeMapping.put("js","application/javascript");
            mimeMapping.put("png ","image/png");
            mimeMapping.put("gif","image/gif");
            mimeMapping.put("gif","image/gif");
            String ext= fileName.substring(fileName.lastIndexOf(".")+1);
            String maps=mimeMapping.get(ext);


            response.addHeader("Content-Type",maps);
            response.addHeader("Content-Length",file.length()+"");
        }else {
            response.setStausCode(404);
            response.setStausReason("Not Found");

            file=new File("./webapps/root/404.html");
            response.setContentFile(file);
            response.addHeader("Content-Type","text/html");
            response.addHeader("Content-Length",file.length()+"");

        }
        response.addHeader("Server","WebServer");
    }
}
